﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;
using System.Text;

public partial class Controls_Activity_SelectGood : BaseUserControl
{ 
    public GoodItemSelectEventHandler OnGoodItemSelectOk;

    private GoodsCategoryAccess goodsCategoryAccess;

    public EventHandler OnSelect;
    private SqlCodeConfig codeConfig;
    private string cmdGoodsText = string.Format("SELECT T.*,A.SUBJECT AS CategoryName FROM {0} T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=1 ", "IC_Goods");
 

    protected void Page_Load(object sender, EventArgs e)
    {
        goodsCategoryAccess = new GoodsCategoryAccess(base.Connection);
        //if (!IsPostBack)
        {
            DataSet ds = goodsCategoryAccess.LoadTreeData(true, false);
            treeView.Nodes.Clear();
            DataToTree(ds, treeView, null);
            InitLoadData();
        }
        OnSelect += new EventHandler(btnSelect_Click);
    }

    private void InitLoadData()
    {
        //获取仓库 
        S_Storage.Items.Clear();
        S_GroupCode.Items.Clear();
        codeConfig = new SqlCodeConfig(this.Connection);
        DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_GoodStorage);
        this.BindDropDownList(S_Storage, ds, true);
        ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_BMZB);
        this.BindDropDownList(S_GroupCode, ds, true);

    }
    #region 选择具体项信息

    protected void btnSelect_Click(object sender, EventArgs e)
    { 
        hfModalPopup.Value = "SelectItem";
        literalModalPopup.Text = "请选择物料项";
        gridViewSelectItems.Visible = true;
        FillGirdViewSelectItems(0, cmdGoodsText);
        modalPopup.Show();
    }
    protected void FillGirdViewSelectItems(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdSelectItemsText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "cmdSelectItemsText"] = cmdText;
        gridViewSelectItems.ShowFooter = true;
        gridViewSelectItems.NavigationData = splitPage.GetNavigationData(currentPage);
        gridViewSelectItems.DataSource = ds.Tables[0];
        gridViewSelectItems.DataBind();
    }
    protected void gridViewSelectItems_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdViewSelectItems(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdSelectItemsText"].ToString());
    }


    protected void gridViewSelectItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "~/PMSWeb/GoodDetail.aspx?GoodsID=" + ((HiddenField)e.Row.Cells[0].Controls[1]).Value;
        }
    }
    /// <summary>
    /// 数据集转换到节点
    /// </summary>
    /// <param name="dataSet"></param>
    /// <param name="treeView"></param>
    /// <param name="node"></param>
    private void DataToTree(DataSet dataSet, TreeView treeView, TreeNode node)
    {
        String filter;
        if (node != null)
            filter = "ParentID = '" + node.Value + "'";
        else
            filter = "ParentID = '0'";

        for (int i = dataSet.Tables[0].Select(filter, "OrderIndex").Length - 1; i >= 0; i--)
        {
            DataRow row = dataSet.Tables[0].Select(filter, "OrderIndex")[i];
            TreeNode child = new TreeNode();
            child.Value = row["NODEID"].ToString();
            child.Text = row["SUBJECT"].ToString();
            //child.NavigateUrl = "#";

            if (node != null)
            {
                node.ChildNodes.Add(child);
                if (node.Depth < 1)
                {
                    node.Expand();
                }
                else
                {
                    node.Collapse();
                }
            }
            else
                treeView.Nodes.Add(child);
            DataToTree(dataSet, treeView, child);
        }
    }



    protected void treeView_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (treeView.SelectedNode == null)
        {
            return;
        }
        string nodeid = treeView.SelectedNode.Value;
        string sql = cmdGoodsText + " AND T.CategoryID='" + nodeid + "' AND T.GoodsID NOT IN(SELECT GoodsID FROM " + SessionManager.GetValue(PMSConst.m_TableItemName) + " WHERE  " + SessionManager.GetValue(PMSConst.m_SubKey) + "='" + SessionManager.GetValue(PMSConst.m_SubValue) + "')";
        FillGirdViewSelectItems(0, sql);
        modalPopup.Show();
    }
    public void btnSearchGood_Click(object sender, EventArgs e)
    {
        StringBuilder sql = sql = new StringBuilder(cmdGoodsText);
        if (!string.IsNullOrEmpty(S_Storage.SelectedValue))
        {
            sql.Append(" AND T.Storage ='").Append(S_Storage.SelectedValue).Append("'");
        }
        if (!string.IsNullOrEmpty(S_GroupCode.SelectedValue))
        {
            sql.Append(" AND T.GoodsID in (select GoodID from IC_GroupGood where GroupCode ='").Append(S_GroupCode.SelectedValue).Append("')");
        }
        if (!string.IsNullOrEmpty(S_Subject.Text))
        {
            sql.Append(" AND T.Subject like '%").Append(S_Subject.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_GoodsCode.Text))
        {
            sql.Append(" AND T.GoodsCode like '%").Append(S_GoodsCode.Text).Append("%'");
        }
        if (treeView.SelectedNode != null)
        {
            sql.Append(" AND T.CategoryID = '").Append(treeView.SelectedNode.Value).Append("'");
        }
        sql.Append(" ORDER BY T.CREATETIME DESC");
        hfModalPopup.Value = "SelectItem";
        literalModalPopup.Text = "请选择物料项";
        gridViewSelectItems.Visible = true;
        FillGirdViewSelectItems(0, sql.ToString());
        modalPopup.Show();
    }
    protected void btnModalPopupOK_Click(object sender, EventArgs e)
    {
        StringBuilder str = new StringBuilder();

        for (int i = 0; i < gridViewSelectItems.Rows.Count; i++)
        {
            HtmlInputCheckBox ck = ((HtmlInputCheckBox)gridViewSelectItems.Rows[i].Cells[0].FindControl("Check_GoodsID"));
            if (ck.Checked)
            {
                str.Append("'").Append(ck.Value).Append("',");
            }
        }
        if (str.Length == 0)
        {
            base.Alert("请选择物料,否则点击取消");
            modalPopup.Show();
            return;
        }
        else
        {
            str = str.Remove(str.Length - 1, 1);
            DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdGoodsText + " and t.GoodsID in(" + str.ToString() + ")");

            //大概是这个意思
            if (OnGoodItemSelectOk != null)
            {
                GoodItemSelectEventArgs ev = new GoodItemSelectEventArgs();
                ev.SelectDataSet = ds;
                ev.SelectedRow = ds.Tables[0].Select();
                OnGoodItemSelectOk(this.ID, ev);
            }  
        }
    }

    #endregion 
}
